package org.ns.framework.datasource.utils;

public class DBSourceUtils {

	/**
	 * 获得数据源名称. 会增加一个后缀名 datasourceName+".suffix"
	 * 
	 * 如果已经存在后缀, 则不会追加后缀.
	 * 
	 * @param datasourceName
	 * @param suffix
	 * @return
	 */
	public static String getSourceName(String datasourceName, String suffix) {
		if (datasourceName.startsWith("##")) { // 如果数据源名字是 ##开头
			datasourceName = datasourceName.substring(2).trim(); // 获得源名称
		}
		String suffixText = "." + suffix;
		if (datasourceName.endsWith(suffixText)) {
			return datasourceName;
		}
		return datasourceName + suffixText;
	}
	
	/**
	 * 数据源名称增加前缀 prefix>>datasourceName
	 * @param datasourceName
	 * @param prefix
	 * @return
	 */
	public static String getSourceNameAddPrefix(String datasourceName, String prefix) {
		if (datasourceName.startsWith("##")) { // 如果数据源名字是 ##开头
			datasourceName = datasourceName.substring(2).trim(); // 获得源名称
		}
		String prefixText = prefix + ">>";
		if (datasourceName.startsWith(prefixText)) {
			return datasourceName;
		}
		return prefixText + datasourceName ;
	}
	
	
	public static String toSourceName(String datasourceName) {
		if (datasourceName.startsWith("##")) { // 如果数据源名字是 ##开头
			datasourceName = datasourceName.substring(2).trim(); // 获得源名称
		}
		int index = datasourceName.indexOf(">>");
		if (index != -1) {
			datasourceName = datasourceName.substring(index + 2);
		}
		index = datasourceName.indexOf(".");
		if (index != -1) {
			datasourceName = datasourceName.substring(0, index);
		}
		return datasourceName;
	}
	
	public static void main(String[] args) {
		System.out.println(getSourceNameAddPrefix("##default", "redis"));
		System.out.println(getSourceName("##default", "redis"));
	}
}
